package cn.tedu.ivos.application.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.dto.ApplicationQuery;
import cn.tedu.ivos.application.pojo.dto.ApplicationSaveParam;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.application.pojo.vo.ApplicationVO;
import cn.tedu.ivos.application.service.ApplicationService;
import cn.tedu.ivos.audit.mapper.AuditMapper;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

/* @Transactional是Spring提供的一个用于管理事务的注解,用来管理类或方法上的事务行为
* 在对数据库做操作时,可以确保该类中的数据库操作在同一个事务中执行,要么都成功,要么都失败 */
@Transactional
@Slf4j
@Service
public class ApplicationServiceImpl implements ApplicationService {
    @Autowired
    ApplicationMapper applicationMapper;
    @Autowired
    AuditService auditService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AuditMapper auditMapper;
    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public void saveApplication(ApplicationSaveParam applicationSaveParam) {
        log.debug("保存申请单业务参数:{}",applicationSaveParam);
        Application application = new Application();
        BeanUtils.copyProperties(applicationSaveParam,application);
        application.setCreateTime(new Date());
        application.setStatus(ApplicationStatusEnum.PENGDING.getCode());
        /* 遇到了问题:新增申请对应的审批数据时,没有拿到申请单id
        * 原因:执行insert对应的SQL后,并没有把刚生成的申请单id回填到application对象中
        * 解决办法:给这条SQL上加useGeneratedKeys="true" keyProperty="id"属性
        * 效果:JDBC自动回填此申请单id到application对象的id属性中,再传给审批,审批就有申请单id了 */
        applicationMapper.insert(application);

        //还需要调用审批业务层,在创建好申请单后,为此申请单创建对应1~2条审批单数据
        auditService.insertAudit(application);
    }

    @Override
    public List<ApplicationVO> selectApplication(ApplicationQuery applicationQuery) {
        log.debug("查询申请单业务参数:{}",applicationQuery);
        List<ApplicationVO> list = applicationMapper.selectApplication(applicationQuery);
        //遍历list,为每个VO对象补全审批人数据
        for(int i = 0; i < list.size(); i++){
            ApplicationVO applicationVO = list.get(i);
            //自定义一个方法用于给申请单VO补全数据
            assignAuditUserList(applicationVO);
        }
        return list;
    }

    @Override
    public void cancel(Long id) {
        log.debug("撤销申请单业务:{}",id);
        //业务1:将申请单的状态改为"撤销"
        Application application = new Application();
        application.setId(id);
        application.setStatus(ApplicationStatusEnum.CANCEL.getCode());
        application.setUpdateTime(new Date());
        applicationMapper.update(application);
        //业务2:将此申请单对应的所有审批单删除
        auditMapper.deleteByApplicationId(id);
    }

    @Override
    public void distribute(Long applicationId, Long vehicleId) {
        log.debug("分配车辆业务:{},{}",applicationId,vehicleId);
        Application application = new Application();
        application.setId(applicationId);
        application.setVehicleId(vehicleId);
        application.setStatus(ApplicationStatusEnum.ALLOCATION.getCode());
        application.setUpdateTime(new Date());
        applicationMapper.update(application);

        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setStatus("2");//设置车辆状态为占用
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }

    @Override
    public void back(Long applicationId, Long vehicleId) {
        log.debug("还车业务:{},{}",applicationId,vehicleId);
        Application application = new Application();
        application.setId(applicationId);
        /* 方案1:保留车辆id方便后期追溯车辆使用情况 */
        //application.setVehicleId(vehicleId);
        /* 方案2:还车将车辆id置为null */
        application.setVehicleId(null);
        application.setStatus(ApplicationStatusEnum.END.getCode());
        application.setUpdateTime(new Date());
        //对于方案2来说,如果要设置null值,那么需要新写一个SQL
        applicationMapper.back(application);

        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setStatus("1");//设置为空闲
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }

    /**
     * 为申请单VO补全审批人信息,此方法并不会产生额外的申请单VO!
     * List<Long> auditUserIdList; //[106,103]
     * String auditUsernameList; //"moly,tom"
     * @param applicationVO
     */
    private void assignAuditUserList(ApplicationVO applicationVO) {
        //1.准备空集合,分别用来保存当前传入申请单对应审批人的id与姓名
        List<Long> auditUserIdList = new ArrayList<>();
        List<String> auditUsernameList = new ArrayList<>();
        //2.获取当前传入的申请单id,查询批此申请单的所有审批单VO
        List<AuditVO> auditVOList =
                auditService.selectAuditByApplicationId(applicationVO.getId());
        //3.依次遍历取出每一个审批单对象
        for(int i = 0; i < auditVOList.size(); i++){
            AuditVO auditVO = auditVOList.get(i);
            //4.获取当前遍历到的审批单VO中的审批人数据
            Long id = auditVO.getAuditUserId();
            auditUserIdList.add(id);
            //5.根据审批人id,查出审批人姓名
            UserVO userVO = userMapper.selectById(id);
            auditUsernameList.add(userVO.getUsername());
        }
        //6.准备一个拼接工具,帮我们把审批人姓名连成一个字符串
        StringJoiner stringJoiner = new StringJoiner(",");
        //7.依次将所有审批人姓名添加到拼接工具中
        for(String username : auditUsernameList){
            stringJoiner.add(username);
        }
        //8.为传入的申请单VO补全数据
        applicationVO.setAuditUserIdList(auditUserIdList);
        applicationVO.setAuditUsernameList(stringJoiner.toString());
    }
}
